const express = require('express');
const router = express.Router();

const Admin = require('../models/admin');
//const crypto = require('crypto');

router.get('/register',function(req,res,next){
res.render('regs',{
    title:'注册页面',
    user:req.session.user
})
})
router.post('/zhuce1', function(req, res) {

	var name = req.body.name;
	Admin.find().count(function(err, count) {
		if(err) {
		 return	res.json({
				error: 1,
				message: '错误'
			});
		}
		Admin.findOne({
			name: name
		}).exec(function(err, data) {
			if(err) {
			return	res.json({
					error: 1,
					message: '错误'
				});
			}
			if(data) {
				return res.json({
					error: 1,
					message: '用户已注册'
				});
				
			}

			var admin = new Admin({
				email: req.body.email,
				name: req.body.name,
				password: req.body.password,
				time: new Date()
			});
			admin.save(function(err) {
				if(err) {
					res.json({
						error: 1,
						message: '错误'
					});
				}
				res.json({
					error: 0,
					message: '商家注册成功'
				});
			})
		})
	})
})

router.get('/log',function(req,res,next){
  res.render('log',{
    title:'登录页面',
    user:req.session.user
  })
})

router.post('/denglu1', function(req, res) {
//	console.log(req.body);
	var name = req.body.name;
	var password = req.body.password;
	Admin.findOne({
		name: name
	}).exec(function(err, data) {
		if(err) {
		return	res.json({
				error: 1,
				message: '错误'
			});
		}
		if(password != data.password) {
		return	res.json({
				error: 1,
				message: '密码错误，请重新输入'
			});
		}
		if(!data) {
		return	res.json({
				error: 1,
				message: '用户不存在,请注册...'
			});

		}

		req.session.user = data;
//		console.log(req.session.user);
		res.json({
			error: 0,
			message: '商家登陆成功！'
		});
	})
})

router.get('/tuichu', function(req, res) {
	req.session.user = null;
	 res.render('log',{
    title:'登录页面',
  })
})

module.exports = router;